<template>
  <div ref="wrapper" @mouseenter="stopScroll" @mouseleave="startScroll">
    <slot></slot>
  </div>
</template>

<script lang="ts" setup>
import {nextTick, onMounted, onUnmounted, ref, toRefs} from 'vue'
import gsap from 'gsap'

const props = defineProps({
  tableCellHeight: {
    type: Number,
    default: 40
  }
})

const {tableCellHeight} = toRefs(props)

const wrapper = ref<HTMLElement>()

const getTableBody = () => {
  // return wrapper.value.querySelector('.el-table__inner-wrapper') as HTMLElement
  return wrapper.value.querySelector('.el-scrollbar__wrap') as HTMLElement

}

let desIndex = 0

let isScroll = true
let gsapInstance: gsap.core.Tween
const scroll = () => {
  gsapInstance?.kill()
  const tableBody = getTableBody()
  const startObj = {
    top: tableBody.scrollTop
  }
  let toTop = ++desIndex * tableCellHeight.value
  let duration = 2
  if(tableBody.scrollHeight===tableBody.clientHeight){
    return
  }
  if (toTop > tableBody.scrollHeight - tableBody.clientHeight) {
    tableBody.scrollTop = 0
    desIndex = 0
    toTop = 0
    duration = 0
  }
  gsapInstance = gsap.to(startObj, {
    duration,
    top: toTop,
    ease: 'linear',
    onUpdate: () => {
      tableBody.scrollTop = startObj.top
    },
    onComplete: () => {
      gsapInstance?.kill()
      if (isScroll) {
        scroll()
      }
    }
  })
}
const startScroll = () => {
  gsapInstance?.kill()
  const tableBody = getTableBody()
  desIndex = Math.ceil(tableBody.scrollTop / tableCellHeight.value)
  isScroll = true
  scroll()
}

const stopScroll = () => {
  gsapInstance?.kill()
  isScroll = false
}

onMounted(() => {
  setTimeout(() => {
    startScroll()
  },1000)
})

onUnmounted(() => {
  isScroll = false
  gsapInstance?.kill()
  gsapInstance = null
})
</script>

<style scoped></style>
